$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '1') {
        window.location.href = '../index.html';
        return;
    }

    // 加载订单列表
    loadOrders();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        localStorage.clear();
        window.location.href = '../index.html';
    });

    // 添加订单处理确认模态框
    $('body').append(`
        <div id="orderActionModal" class="modal" style="display: none;">
            <div class="modal-content">
                <h3 id="modalTitle"></h3>
                <div class="order-action-preview">
                    <div class="order-info"></div>
                </div>
                <div class="modal-actions">
                    <button class="primary-btn confirm-action-btn">确认</button>
                    <button class="secondary-btn cancel-action-btn">取消</button>
                </div>
            </div>
        </div>
    `);

    // 添加模态框样式
    $('<style>').text(`
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .modal h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 1.5rem;
            text-align: center;
        }
        
        .order-action-preview {
            margin-bottom: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 6px;
            border: 1px solid #eee;
        }
        
        .order-info {
            color: #666;
            line-height: 1.6;
        }
        
        .modal-actions {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        
        .modal-actions button {
            padding: 10px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
            min-width: 120px;
        }
        
        .primary-btn {
            background-color: #4CAF50;
            color: white;
        }
        
        .primary-btn:hover {
            background-color: #45a049;
        }
        
        .secondary-btn {
            background-color: #666;
            color: white;
        }
        
        .secondary-btn:hover {
            background-color: #555;
        }
        
        .primary-btn.accept {
            background-color: #4CAF50;
        }
        
        .primary-btn.reject {
            background-color: #dc3545;
        }
        
        #orderActionModal .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        
        #orderActionModal .info-row:last-child {
            border-bottom: none;
        }
        
        #orderActionModal .info-label {
            color: #666;
            font-weight: 500;
        }
        
        #orderActionModal .info-value {
            color: #333;
            font-weight: 500;
        }
        
        #orderActionModal .text-success {
            color: #4CAF50;
        }
        
        #orderActionModal .text-danger {
            color: #dc3545;
        }
        
        #orderActionModal .warning-text {
            color: #856404;
            background-color: #fff3cd;
            padding: 10px;
            border-radius: 4px;
            margin-top: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: center;
        }
        
        #orderActionModal .warning-icon {
            font-size: 1.2em;
        }
    `).appendTo('head');

    // 绑定模态框按钮事件
    $('.cancel-action-btn').click(function() {
        $('#orderActionModal').hide();
    });
});

function loadOrders() {
    const sellerId = localStorage.getItem('userId');
    
    $.ajax({
        url: `/api/order/seller/${sellerId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const orders = response.data;
                const container = $('#ordersList');
                container.empty();
                
                if (orders.length === 0) {
                    container.html(`
                        <div class="empty-orders">
                            <h3>暂无订单</h3>
                            <p>等待买家下单...</p>
                        </div>
                    `);
                    return;
                }
                
                orders.forEach(order => {
                    container.append(`
                        <div class="order-card">
                            <div class="order-header">
                                <div class="order-info">
                                    <div class="order-id">订单号: ${order.orderId}</div>
                                    <div class="buyer-info">买家: ${order.buyerName}</div>
                                </div>
                                <div class="order-status">${getStatusText(order.status)}</div>
                            </div>
                            <div class="order-details" id="details-${order.orderId}">
                                <!-- 订单详情将通过AJAX加载 -->
                            </div>
                            <div class="order-footer">
                                <div class="order-time">下单时间: ${new Date(order.orderTime).toLocaleString()}</div>
                                <div class="order-actions">
                                    ${order.status === 1 ? `
                                        <button class="accept-btn" onclick="handleOrder(${order.orderId}, 2)">接受订单</button>
                                        <button class="reject-btn" onclick="handleOrder(${order.orderId}, 3)">拒绝订单</button>
                                    ` : ''}
                                </div>
                                <div class="order-total">总计: ¥${order.totalMoney.toFixed(2)}</div>
                            </div>
                        </div>
                    `);
                    
                    // 加载订单详情
                    loadOrderDetails(order.orderId);
                });
            } else {
                showMessage(response.message || '加载订单失败', 'error');
            }
        },
        error: function() {
            showMessage('加载订单失败，请重试', 'error');
        }
    });
}

function loadOrderDetails(orderId) {
    $.ajax({
        url: `/api/order/details/${orderId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const details = response.data;
                const container = $(`#details-${orderId}`);
                
                details.forEach(detail => {
                    container.append(`
                        <div class="order-item">
                            <div class="item-name">${detail.commodityName}</div>
                            <div class="item-price">¥${detail.price.toFixed(2)} × ${detail.amount}</div>
                            <div class="item-total">¥${detail.money.toFixed(2)}</div>
                        </div>
                    `);
                });
            }
        }
    });
}

function handleOrder(orderId, status) {
    const action = status === 2 ? '接受' : '拒绝';
    const modal = $('#orderActionModal');
    
    // 设置模态框内容
    modal.find('#modalTitle').text(`确认${action}订单`);
    modal.find('.order-info').html(`
        <div class="info-row">
            <span class="info-label">订单编号</span>
            <span class="info-value">${orderId}</span>
        </div>
        <div class="info-row">
            <span class="info-label">操作类型</span>
            <span class="info-value ${status === 2 ? 'text-success' : 'text-danger'}">${action}订单</span>
        </div>
        <div class="info-row warning-text">
            <i class="warning-icon">⚠️</i>
            <span>此操作不可撤销，请确认。</span>
        </div>
    `);
    
    // 设置确认按钮样式和事件
    modal.find('.confirm-action-btn')
        .removeClass('accept reject')
        .addClass(status === 2 ? 'accept' : 'reject')
        .text(`确认${action}`)
        .off('click')
        .on('click', function() {
            modal.hide();
            submitOrderAction(orderId, status);
        });
    
    // 显示模态框
    modal.css('display', 'flex');
}

function submitOrderAction(orderId, status) {
    $.ajax({
        url: '/api/order/update/status',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            orderId: orderId,
            status: status
        }),
        success: function(response) {
            if (response.code === 200) {
                showMessage(status === 2 ? '已接受订单' : '已拒绝订单', 'success', 1000);
                loadOrders();
            } else {
                showMessage(response.message || '操作失败', 'error', 1000);
            }
        },
        error: function() {
            showMessage('操作失败，请重试', 'error', 1000);
        }
    });
}

function getStatusText(status) {
    switch(status) {
        case 1: return '<span class="status-pending">待处理</span>';
        case 2: return '<span class="status-accepted">已接受</span>';
        case 3: return '<span class="status-rejected">已拒绝</span>';
        default: return '<span class="status-unknown">未知状态</span>';
    }
}

function showMessage(message, type = 'success', duration = 2000) {
    const messageDiv = $('<div>')
        .addClass('message')
        .addClass(type)
        .text(message)
        .css('opacity', 0);

    $('body').append(messageDiv);
    messageDiv.animate({ opacity: 1 }, 300);

    setTimeout(() => {
        messageDiv.animate({ opacity: 0 }, 300, function() {
            $(this).remove();
        });
    }, duration);
} 